package com.mdn.steelcase.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mdn.steelcase.model.DocumentEntity;
import com.mdn.steelcase.service.DocumentService;

@Controller
@RequestMapping("/connector")
public class ConnectorController {

	protected static final Logger LOGGER = Logger.getLogger( ConnectorController.class.getName() );

	@Autowired
	DocumentService documentService;

	@RequestMapping(value = "/init", method = RequestMethod.GET)
	public @ResponseBody String init() {
		DocumentEntity about_connector = new DocumentEntity("about_connector", "Introduzca el contenido para la respuesta del comando about_connector.");
		DocumentEntity get_bookings = new DocumentEntity("get_bookings", "Introduzca el contenido para la respuesta del comando get_bookings.");
		DocumentEntity add_booking = new DocumentEntity("add_booking", "Introduzca el contenido para la respuesta del comando add_booking.");
		DocumentEntity edit_booking = new DocumentEntity("edit_booking", "Introduzca el contenido para la respuesta del comando edit_booking.");
		DocumentEntity delete_booking = new DocumentEntity("delete_booking", "Introduzca el contenido para la respuesta del comando delete_booking.");
		documentService.save(about_connector);
		documentService.save(get_bookings);
		documentService.save(add_booking);
		documentService.save(edit_booking);
		documentService.save(delete_booking);
		return "OK";
	}
	@RequestMapping( method = {RequestMethod.GET, RequestMethod.POST}, produces="application/xml; charSet=UTF-8")
	public @ResponseBody String entryPoint(HttpServletRequest req) {		
		String command = req.getParameter("command");
		if(command != null){
			final DocumentEntity document = documentService.findSingleByColumn("name", command); 
			if(document != null){
				LOGGER.info("OK QueryString: " + req.getQueryString());
				return document.getContent().
						replaceAll("\\{date\\}", new SimpleDateFormat("yyyyMMdd").format(new Date())).
						replaceAll("\\{time\\}", new SimpleDateFormat("HHmmss").format(new Date()));
			}else{
				LOGGER.severe("NO DOCUMENT QueryString: " + req.getQueryString());
				return "<error>no se ha encontrado el documento para el comando " + command + "</error>";
			}
		}else{
			LOGGER.severe("BAD REQUEST QueryString: " + req.getQueryString());
			return "<error>No se ha informado de ningún comando</error>";
		}
	}
}
